package com.myhome.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.myhome.domain.Sms;
import com.myhome.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author QYiXin
 * @Date 2021 10 18 21 02
 **/
@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    MailProperties mailProperties;
    @Autowired
    TemplateEngine templateEngine;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public Boolean sendEmail(Sms sms) {
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(msg);
        try {
            mimeMessageHelper.setFrom(mailProperties.getUsername());
            mimeMessageHelper.setTo(sms.getEmail());
            mimeMessageHelper.setSubject("用户信息修改");
            mimeMessageHelper.setSentDate(new Date());
            Context context = new Context();
            String code = RandomUtil.randomNumbers(6);
            redisTemplate.opsForValue().set("SMS"+sms.getMobile()+"CODE",code,1, TimeUnit.MINUTES);
            context.setVariable("emailCode",code);
            String mail = templateEngine.process("mail", context);
            mimeMessageHelper.setText(mail,true);
            javaMailSender.send(msg);
        } catch (Exception e) {
            System.out.println("发送失败"+e.getMessage());
            return false;
        }
        return true;
    }
}
